package hasthi.coordinator;

import static hasthi.common.constants.HasthiConstants.ASSIGN_RESOURCE_ACTION;

import java.util.Iterator;
import java.util.Set;

import hasthi.common.AbstractMessageBag;
import hasthi.common.HasthiException;
import hasthi.container.MessageContext;
import hasthi.container.SimpleMessageContext;
import hasthi.manager.AssignResourcesDocument;
import hasthi.manager.ManagerAddress;
import hasthi.manager.AssignResourcesDocument.AssignResources;
import hasthi.manager.AssignResourcesDocument.AssignResources.ResourceData;

import javax.xml.namespace.QName;

public class ManageMeMessageBag extends AbstractMessageBag<ManageMeRequest> {
    private CoordinatorContext coordinatorContext;

    public ManageMeMessageBag(CoordinatorContext coordinatorContext) {
        super(coordinatorContext.getMyManagerContext().getUnicastContainer());
        this.coordinatorContext = coordinatorContext;
    }

    @Override
    protected void processBatch(Set<ManageMeRequest> list) throws HasthiException {
        if (list.size() == 0) {
            return;
        }

        RemoteManagerContext resourceCaretaker = null;
        ManagerAddress address = null;
        // Assign the resource to the selected Manager

        AssignResourcesDocument assignResourceDocument = AssignResourcesDocument.Factory
                .newInstance();
        final AssignResources assignResources = assignResourceDocument.addNewAssignResources();

        for (ManageMeRequest request : list) {
            if(resourceCaretaker == null){
                resourceCaretaker = coordinatorContext.findBestManager4Resource(request.name);
                address = resourceCaretaker.getAddress();
            }
            ResourceData resourceData = assignResources.addNewResourceData();
            resourceData.setManagementEndpoint(request.managementAgentUrl);
            resourceData.setName(request.name);
        }
        MessageContext requestMessage = new SimpleMessageContext(assignResourceDocument, address
                .getSoapAddress(), ASSIGN_RESOURCE_ACTION);
        soapContainer.sendReceive(requestMessage);

    }

    public void addManagemeRequest(QName name, String managementAgentUrl) throws HasthiException {
        add(new ManageMeRequest(name, managementAgentUrl));
    }
}
